/*
 * AbstractTemplateRenderedResource.java
 *
 * Copyright 2013 Jack Leow
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package my.edu.clhs.springframework.core.io;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.Resource;

/**
 * Base class for {@link Resource}s that represents the rendition of
 * applying templates to models.
 *
 * @author Jack Leow
 * @since January 2013
 */
public abstract class AbstractTemplateRenderedResource<T>
        extends AbstractResource {
    private final Resource templateResource;
    
    private final Charset charset;
    
    private final Map<String,?> model;
    
    public AbstractTemplateRenderedResource(
            Resource templateResource, Charset charset, Map<String,?> model) {
        if (templateResource == null) {
            throw new NullPointerException(
                "templateResource must not be null."
            );
        }
        if (charset == null) {
            throw new NullPointerException("charset must not be null.");
        }
        if (model == null) {
            throw new NullPointerException("model must not be null.");
        }
        this.templateResource = templateResource;
        this.charset = charset;
        this.model = model;
    }
    
    public AbstractTemplateRenderedResource(
            Resource template, Map<String,?> model) {
        this(template, Charset.defaultCharset(), model);
    }
    
    @Override
    public String getDescription() {
        return templateResource.getDescription() + " (rendered)";
    }
    
    /**
     * Creates the template object from the given raw template content.
     * 
     * @param templateResourceInputStream
     *  Bytes of the template resource. Implementations do not have to
     *  close this resource.
     * @param charset Character set of the template resource.
     * @return The template object.
     */
    protected abstract T createTemplate(
            InputStream templateResourceInputStream, Charset charset)
            throws IOException;
    
    /**
     * Applies the given template to the model.
     * 
     * @param template The template object.
     * @param charset The character set of the output.
     * @param model The model to apply the template to.
     * @return The applied template.
     */
    protected abstract InputStream applyTemplate(
            T template, Charset charset, Map<String,?> model)
            throws IOException;
    
    private Long templateLoadMillis = null;
    private T template;
    
    @Override
    public final InputStream getInputStream() throws IOException {
        Long lastModifiedMillis = null;
        if (templateLoadMillis != null) {
            try {
                lastModifiedMillis = templateResource.lastModified();
            } catch (IOException e) {
                // do nothing
            }
        }
        if (templateLoadMillis == null || lastModifiedMillis == null ||
                lastModifiedMillis > templateLoadMillis) {
            InputStream is = templateResource.getInputStream();
            try {
                long justBeforeMillis = System.currentTimeMillis();
                template = createTemplate(is, charset);
                templateLoadMillis = justBeforeMillis;
            } finally {
                is.close();
            }
        }
        
        return applyTemplate(template, charset, model);
    }
}